﻿using System;
using System.Collections.Generic;
using Opalis.QuickIntegrationKit;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.Collections;

namespace Active_Directory
{
    [OpalisObject("Create Security Group",ShowFilters=false)]
    class CreateSecurityGroup : IOpalisObject
    {
        private ConnectionCredentials credentials;

        [OpalisConfiguration]
        public ConnectionCredentials Credentials
        {
            get { return credentials; }
            set { credentials = value; }
        }

        public void Design(IOpalisDesigner designer)
        {
            designer.AddInput("Group Container OU LDAP Path").WithDefaultValue("LDAP://OU=ContainerOU,DC=Contoso,DC=Com");
            designer.AddInput("Group Name").WithDefaultValue("GroupName");
            designer.AddOutput("Group LDAP Path").AsString();
        }

        public void Execute(IOpalisRequest request, IOpalisResponse response)
        {
            string containingOU = request.Inputs["Group Container OU LDAP Path"].AsString();
            string groupName = request.Inputs["Group Name"].AsString();

            string groupDn = "LDAP://CN=" + groupName + "," + containingOU.Substring(7);

            if (!DirectoryEntry.Exists(groupDn))
            {
                try
                {
                    DirectoryEntry entry = new DirectoryEntry(containingOU, credentials.UserName + "@" + credentials.Domain, credentials.Password);
                    DirectoryEntry group = entry.Children.Add("CN=" + groupName, "group");
                    group.Properties["sAmAccountName"].Value = groupName;
                    group.CommitChanges();
                    response.Publish("Group DN", groupDn);
                }
                catch (System.DirectoryServices.DirectoryServicesCOMException E)
                {
                    response.LogErrorMessage(E.Message.ToString());
                }
            }
            else
            {
                response.LogErrorMessage("Group already exists with DN " + groupDn);
            }
        }
    }
}
